package enumandlambda;

import java.util.Random;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

/**
 * @author shkstart
 * @create 2022-12-02-15:20
 */
public class zuoye {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        //记录开始时间
        long stime = System.currentTimeMillis();

        int []arr = new int [1000000];
        //不能放进for循环，会new太多次
        Random random = new Random();
        for (int i = 0; i < arr.length; i++) {
            //使随机数范围在1-100之间
            arr[i] = random.nextInt(100)+1;
        }
        FutureTask<Integer> futureTask1 = new FutureTask<>(new Callable<Integer>() {
            @Override
            public Integer call() throws Exception {
                int  count1=0;
                for (int i = 0; i <arr.length ; i+=2) {
                    count1+=arr[i];
                }
                System.out.println("线程1："+ count1);
                return count1;
            }
        });
        FutureTask<Integer> futureTask2 = new FutureTask<>(new Callable<Integer>() {
            @Override
            public Integer call() throws Exception {
                int  count2=0;
                for (int i = 1; i <arr.length ; i+=2) {
                    count2+=arr[i];
                }
                System.out.println("线程2："+ count2);
                return count2;
            }
        });

        Thread t1 = new Thread(futureTask1);
        Thread t2 = new Thread(futureTask2);

        t1.start();
        t2.start();
//  正常情况下都需要+ join
//        t1.join();
//        t2.join();
        //但是get方法特殊，只有执行完成之后才能有返回值
        //相当与自带join方法
        //普通方法一定需要Join
        int tt1 = futureTask1.get();
        int tt2 = futureTask2.get();

        System.out.println(tt1+tt2);
        //记录完成时间
        long etimr = System.currentTimeMillis();
        System.out.println("最终执行时间是"+(etimr-stime));
        




    }
}
